import axios from 'axios'
import { hasToken, getToken } from './storage'
import { message } from 'antd'
import history from './history'
import { removeToken } from '@/utils/storage'
import Store from '../store/index'
const instance = axios.create({
  baseURL: 'http://geek.itheima.net/v1_0/',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (hasToken()) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (!error.response) {
      message.error('网络异常')
    } else if (error.response.status === 401) {
      message.error('身份过期，请重新登录')
      removeToken()
      Store.dispatch({ type: 'request/clearUser' })
      history.push('/login')
    }
    return Promise.reject(error)
  }
)

export default instance
